<template>
  <div class="waybill-recharge">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>面单充值</h2>
      <el-button type="primary" @click="showAddDialog">
        添加充值记录
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="店铺名/客户姓名/交易单号"
            clearable
            @keyup.enter="handleSearch"
            style="width: 240px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="所属平台">
          <el-select
            v-model="searchForm.platform"
            placeholder="全部平台"
            clearable
            style="width: 120px"
          >
            <el-option label="淘宝" value="taobao" />
            <el-option label="拼多多" value="pinduoduo" />
            <el-option label="抖音" value="douyin" />
            <el-option label="小红书" value="xiaohongshu" />
            <el-option label="京东" value="jingdong" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司">
          <el-select
            v-model="searchForm.expressCompany"
            placeholder="全部快递"
            clearable
            style="width: 120px"
          >
            <el-option label="中通" value="zhongtong" />
            <el-option label="韵达" value="yunda" />
            <el-option label="申通" value="shentong" />
            <el-option label="圆通" value="yuantong" />
            <el-option label="邮政" value="youzheng" />
            <el-option label="极兔" value="jitu" />
            <el-option label="顺丰" value="shunfeng" />
            <el-option label="德邦" value="debang" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易状态">
          <el-select
            v-model="searchForm.paymentStatus"
            placeholder="全部状态"
            clearable
            style="width: 120px"
          >
            <el-option label="已付" value="paid" />
            <el-option label="未付" value="unpaid" />
            <el-option label="部分付" value="partial" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch"> 搜索 </el-button>
          <el-button @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 充值记录列表 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="table-header">
          <span>充值记录</span>
          <div class="table-info">共 {{ pagination.total }} 条记录</div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="rechargeRecords"
        stripe
        style="width: 100%"
      >
        <el-table-column label="序号" width="60" align="center">
          <template #default="{ $index }">
            {{ (pagination.page - 1) * pagination.limit + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="shopName" label="所属店铺" min-width="120" />
        <el-table-column prop="platform" label="所属平台" width="100">
          <template #default="{ row }">
            <el-tag :type="getPlatformTagType(row.platform)" size="small">
              {{ getPlatformLabel(row.platform) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expressCompany" label="快递公司" width="100">
          <template #default="{ row }">
            {{ getExpressLabel(row.expressCompany) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="quantity"
          label="充值数量"
          width="100"
          align="center"
        />
        <el-table-column prop="customerName" label="所属客户" min-width="100" />
        <el-table-column label="交易状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusType(row)" size="small">
              {{ getPaymentStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="交易时间" width="150">
          <template #default="{ row }">
            {{ row.transactionTime ? formatDate(row.transactionTime) : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button
                type="primary"
                size="small"
                @click="showEditDialog(row)"
              >
                编辑
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="showDetailDialog(row)"
              >
                详情
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑充值记录对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="rechargeFormRef"
        :model="rechargeForm"
        :rules="rechargeRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属客户" prop="customerId">
              <el-select
                v-model="rechargeForm.customerId"
                placeholder="请选择客户"
                filterable
                style="width: 100%"
                @change="handleCustomerChange"
              >
                <el-option
                  v-for="customer in customers"
                  :key="customer._id"
                  :label="customer.name"
                  :value="customer._id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属店铺" prop="shopId">
              <el-select
                v-model="rechargeForm.shopId"
                placeholder="请选择店铺"
                filterable
                style="width: 100%"
                @change="handleShopChange"
              >
                <el-option
                  v-for="shop in availableShops"
                  :key="shop._id"
                  :label="`${shop.shopName} (${getPlatformLabel(
                    shop.platform
                  )})`"
                  :value="shop._id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="快递公司" prop="expressCompany">
              <el-select
                v-model="rechargeForm.expressCompany"
                placeholder="请选择快递公司"
                style="width: 100%"
              >
                <el-option
                  v-for="express in availableExpressCompanies"
                  :key="express"
                  :label="getExpressLabel(express)"
                  :value="express"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="充值数量" prop="quantity">
              <el-input-number
                v-model="rechargeForm.quantity"
                :min="1"
                placeholder="请输入充值数量"
                style="width: 100%"
                @change="calculateAmount"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="面单预充金额">
              <el-input
                :value="rechargeForm.prepaidAmount"
                disabled
                style="width: 100%"
              >
                <template #suffix>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应收金额">
              <el-input
                :value="rechargeForm.totalAmount"
                disabled
                style="width: 100%"
              >
                <template #suffix>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="实收金额" prop="actualAmount">
              <el-input-number
                v-model="rechargeForm.actualAmount"
                :min="0"
                :precision="2"
                placeholder="请输入实收金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易方式" prop="paymentMethod">
              <el-select
                v-model="rechargeForm.paymentMethod"
                placeholder="请选择交易方式"
                style="width: 100%"
              >
                <el-option
                  v-for="method in availablePaymentMethods"
                  :key="method.value"
                  :label="method.label"
                  :value="method.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交易时间" prop="transactionTime">
              <el-date-picker
                v-model="rechargeForm.transactionTime"
                type="datetime"
                placeholder="请选择交易时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认时间" prop="confirmTime">
              <el-date-picker
                v-model="rechargeForm.confirmTime"
                type="datetime"
                placeholder="请选择确认时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="交易单号">
          <div class="transaction-numbers">
            <div
              v-for="(number, index) in rechargeForm.transactionNumbers"
              :key="index"
              class="transaction-number-item"
            >
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-input
                    v-model="rechargeForm.transactionNumbers[index]"
                    placeholder="请输入交易单号"
                  />
                </el-col>
                <el-col :span="4">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeTransactionNumber(index)"
                    >删除</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" size="small" @click="addTransactionNumber"
              >添加交易单号</el-button
            >
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 充值记录详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="充值记录详情" width="700px">
      <el-descriptions :column="2" border v-if="currentRecord">
        <el-descriptions-item label="所属客户">{{
          currentRecord.customerName
        }}</el-descriptions-item>
        <el-descriptions-item label="所属店铺">{{
          currentRecord.shopName
        }}</el-descriptions-item>
        <el-descriptions-item label="所属平台">
          <el-tag :type="getPlatformTagType(currentRecord.platform)">
            {{ getPlatformLabel(currentRecord.platform) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="快递公司">{{
          getExpressLabel(currentRecord.expressCompany)
        }}</el-descriptions-item>
        <el-descriptions-item label="充值数量">{{
          currentRecord.quantity
        }}</el-descriptions-item>
        <el-descriptions-item label="面单预充金额"
          >{{ currentRecord.prepaidAmount }} 元</el-descriptions-item
        >
        <el-descriptions-item label="应收金额"
          >{{ currentRecord.totalAmount }} 元</el-descriptions-item
        >
        <el-descriptions-item label="实收金额"
          >{{ currentRecord.actualAmount || 0 }} 元</el-descriptions-item
        >
        <el-descriptions-item label="交易方式">{{
          getPaymentMethodLabel(currentRecord.paymentMethod)
        }}</el-descriptions-item>
        <el-descriptions-item label="交易状态">
          <el-tag :type="getPaymentStatusType(currentRecord)">
            {{ getPaymentStatusText(currentRecord) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="交易时间">{{
          currentRecord.transactionTime
            ? formatDate(currentRecord.transactionTime)
            : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="确认时间">{{
          currentRecord.confirmTime
            ? formatDate(currentRecord.confirmTime)
            : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="交易单号" :span="2">
          <div
            v-if="
              currentRecord.transactionNumbers &&
              currentRecord.transactionNumbers.length > 0
            "
          >
            <el-tag
              v-for="(number, index) in currentRecord.transactionNumbers"
              :key="index"
              class="number-tag"
            >
              {{ number }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(currentRecord.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import api from "@/utils/api";

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const rechargeRecords = ref([]);
const customers = ref([]);
const shops = ref([]);
const availableShops = ref([]);
const availableExpressCompanies = ref([]);
const availablePaymentMethods = ref([]);
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);
const currentRecord = ref(null);
const rechargeFormRef = ref();

// 搜索表单
const searchForm = reactive({
  search: "",
  platform: "",
  expressCompany: "",
  paymentStatus: "",
});

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 充值表单
const rechargeForm = reactive({
  customerId: "",
  shopId: "",
  expressCompany: "",
  quantity: 1,
  prepaidAmount: 0,
  totalAmount: 0,
  actualAmount: 0,
  paymentMethod: "",
  transactionTime: "",
  confirmTime: "",
  transactionNumbers: [],
});

// 表单验证规则
const rechargeRules = {
  customerId: [
    { required: true, message: "请选择所属客户", trigger: "change" },
  ],
  shopId: [{ required: true, message: "请选择所属店铺", trigger: "change" }],
  expressCompany: [
    { required: true, message: "请选择快递公司", trigger: "change" },
  ],
  quantity: [
    { required: true, message: "请输入充值数量", trigger: "blur" },
    { type: "number", min: 1, message: "充值数量不能小于1", trigger: "blur" },
  ],
  actualAmount: [
    { required: true, message: "请输入实收金额", trigger: "blur" },
    { type: "number", min: 0, message: "实收金额不能小于0", trigger: "blur" },
  ],
  paymentMethod: [
    { required: true, message: "请选择交易方式", trigger: "change" },
  ],
};

// 计算属性
const dialogTitle = computed(() =>
  isEdit.value ? "编辑充值记录" : "添加充值记录"
);

// 获取平台标签
const getPlatformLabel = (platform) => {
  const labels = {
    taobao: "淘宝",
    pinduoduo: "拼多多",
    douyin: "抖音",
    xiaohongshu: "小红书",
    jingdong: "京东",
  };
  return labels[platform] || platform;
};

// 获取平台标签类型
const getPlatformTagType = (platform) => {
  const types = {
    taobao: "warning",
    pinduoduo: "danger",
    douyin: "success",
    xiaohongshu: "info",
    jingdong: "primary",
  };
  return types[platform] || "";
};

// 获取快递公司标签
const getExpressLabel = (express) => {
  const labels = {
    zhongtong: "中通",
    yunda: "韵达",
    shentong: "申通",
    yuantong: "圆通",
    youzheng: "邮政",
    jitu: "极兔",
    shunfeng: "顺丰",
    debang: "德邦",
  };
  return labels[express] || express;
};

// 获取交易方式标签
const getPaymentMethodLabel = (method) => {
  const labels = {
    alipay: "支付宝",
    wechat_pay: "微信支付",
    bank_card: "银行卡",
    cash: "现金",
    refund: "退单",
    transfer: "转单",
    transit_fee: "中转费抵扣",
    other: "其他方式",
  };
  return labels[method] || method;
};

// 获取支付状态类型
const getPaymentStatusType = (record) => {
  const actualAmount = record.actualAmount || 0;
  const totalAmount = record.totalAmount || 0;

  if (actualAmount === 0) return "danger";
  if (actualAmount >= totalAmount) return "success";
  return "warning";
};

// 获取支付状态文本
const getPaymentStatusText = (record) => {
  const actualAmount = record.actualAmount || 0;
  const totalAmount = record.totalAmount || 0;

  if (actualAmount === 0) return "未付";
  if (actualAmount >= totalAmount) return "已付";
  return `${actualAmount}/${totalAmount}`;
};

// 获取客户列表
const fetchCustomers = async () => {
  try {
    const response = await api.get("/customers", { params: { limit: 1000 } });
    customers.value = response.data.customers;
  } catch (error) {
    ElMessage.error("获取客户列表失败");
  }
};

// 获取店铺列表
const fetchShops = async () => {
  try {
    const response = await api.get("/shops", { params: { limit: 1000 } });
    shops.value = response.data.shops;
  } catch (error) {
    ElMessage.error("获取店铺列表失败");
  }
};

// 获取充值记录列表
const fetchRechargeRecords = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      search: searchForm.search,
      platform: searchForm.platform,
      expressCompany: searchForm.expressCompany,
      paymentStatus: searchForm.paymentStatus,
    };

    const response = await api.get("/waybill-recharge", { params });
    rechargeRecords.value = response.data.records;
    pagination.total = response.data.total;
  } catch (error) {
    ElMessage.error("获取充值记录失败");
  } finally {
    loading.value = false;
  }
};

// 处理客户变化
const handleCustomerChange = (customerId) => {
  const customer = customers.value.find((c) => c._id === customerId);
  if (customer) {
    rechargeForm.prepaidAmount = customer.prepaidAmount || 0;

    // 筛选该客户的店铺
    availableShops.value = shops.value.filter(
      (shop) => shop.customerId === customerId
    );

    // 设置可用的交易方式
    const customerMethods = customer.transactionMethods || [];
    availablePaymentMethods.value = [
      { label: "微信支付", value: "wechat_pay" }, // 微信支付放在第一位
      ...customerMethods.map((method) => ({
        label: getPaymentMethodLabel(method.type),
        value: method.type,
      })),
      { label: "退单", value: "refund" },
      { label: "转单", value: "transfer" },
      { label: "中转费抵扣", value: "transit_fee" },
      { label: "其他方式", value: "other" },
    ];

    calculateAmount();
  }

  // 重置店铺选择
  rechargeForm.shopId = "";
  rechargeForm.expressCompany = "";
  availableExpressCompanies.value = [];
};

// 处理店铺变化
const handleShopChange = (shopId) => {
  const shop = shops.value.find((s) => s._id === shopId);
  if (shop) {
    availableExpressCompanies.value = shop.expressCompanies || [];
  }

  // 重置快递公司选择
  rechargeForm.expressCompany = "";
};

// 计算金额
const calculateAmount = () => {
  rechargeForm.totalAmount =
    (rechargeForm.quantity || 0) * (rechargeForm.prepaidAmount || 0);
};

// 添加交易单号
const addTransactionNumber = () => {
  rechargeForm.transactionNumbers.push("");
};

// 删除交易单号
const removeTransactionNumber = (index) => {
  rechargeForm.transactionNumbers.splice(index, 1);
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchRechargeRecords();
};

// 重置搜索
const handleReset = () => {
  searchForm.search = "";
  searchForm.platform = "";
  searchForm.expressCompany = "";
  searchForm.paymentStatus = "";
  pagination.page = 1;
  fetchRechargeRecords();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchRechargeRecords();
};

const handleCurrentChange = (page) => {
  pagination.page = page;
  fetchRechargeRecords();
};

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (record) => {
  isEdit.value = true;
  currentRecord.value = record;
  Object.assign(rechargeForm, {
    ...record,
    transactionNumbers: record.transactionNumbers || [],
  });

  // 设置可用选项
  handleCustomerChange(record.customerId);
  handleShopChange(record.shopId);

  dialogVisible.value = true;
};

// 显示详情对话框
const showDetailDialog = (record) => {
  currentRecord.value = record;
  detailDialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(rechargeForm, {
    customerId: "",
    shopId: "",
    expressCompany: "",
    quantity: 1,
    prepaidAmount: 0,
    totalAmount: 0,
    actualAmount: 0,
    paymentMethod: "",
    transactionTime: "",
    confirmTime: "",
    transactionNumbers: [],
  });

  availableShops.value = [];
  availableExpressCompanies.value = [];
  availablePaymentMethods.value = [];

  rechargeFormRef.value?.resetFields();
  rechargeFormRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!rechargeFormRef.value) return;

  try {
    const valid = await rechargeFormRef.value.validate();
    if (!valid) return;
  } catch {
    return;
  }

  submitLoading.value = true;

  try {
    if (isEdit.value) {
      await api.put(
        `/waybill-recharge/${currentRecord.value._id}`,
        rechargeForm
      );
      ElMessage.success("充值记录更新成功");
    } else {
      await api.post("/waybill-recharge", rechargeForm);
      ElMessage.success("充值记录创建成功");
    }

    dialogVisible.value = false;
    fetchRechargeRecords();
  } catch (error) {
    ElMessage.error(error.response?.data?.error || "操作失败");
  } finally {
    submitLoading.value = false;
  }
};

// 删除充值记录
const handleDelete = async (record) => {
  try {
    await ElMessageBox.confirm(`确定要删除这条充值记录吗？`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await api.delete(`/waybill-recharge/${record._id}`);
    ElMessage.success("充值记录删除成功");
    fetchRechargeRecords();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "未知";
  return new Date(dateString).toLocaleString("zh-CN");
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCustomers();
  fetchShops();
  fetchRechargeRecords();
});
</script>

<style lang="scss" scoped>
.waybill-recharge {
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: $text-primary;
      font-size: 20px;
      font-weight: 600;
    }
  }

  .search-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .table-card {
    flex: 1;
    display: flex;
    flex-direction: column;

    :deep(.el-card__body) {
      padding: 20px;
      flex: 1;
      display: flex;
      flex-direction: column;
    }

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      span {
        font-weight: 600;
        color: $text-primary;
        font-size: 16px;
      }

      .table-info {
        color: $text-secondary;
        font-size: 14px;
      }
    }

    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }

    .operation-buttons {
      display: flex;
      gap: 6px;
      white-space: nowrap;
    }
  }

  .transaction-numbers {
    .transaction-number-item {
      margin-bottom: 12px;
    }
  }

  .number-tag {
    margin-right: 8px;
    margin-bottom: 4px;
  }
}

// 确保表格铺满容器
:deep(.el-table) {
  width: 100% !important;
  flex: 1;
}

// 响应式设计
@media (max-width: 768px) {
  .waybill-recharge {
    .page-header {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
    }

    .table-card {
      .operation-buttons {
        flex-direction: column;
        gap: 4px;
      }
    }
  }
}
</style>
